#!/bin/bash

BASE_DIR=/mysql
DATA_DIR=/data
port=3306
online=0


# yum方式安装
function yum_install(){
  rpm -ivh https://repo.mysql.com//mysql80-community-release-el7-2.noarch.rpm
  yum install mysql-community-server -y
  service mysqld start
  service mysqld status
  systemctl enable mysqld
}

function create_user() {
  # create group and user
  groupadd mysql
  useradd  -r -g mysql mysql
}

function tarxz_install(){
  ### 这里需要放下载地址，最好下载下来，用包的形式安装；批量ansible安装
  if [ $online ];then
    URL_Download=https://dev.mysql.com/get/Downloads/MySQL-8.0/mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz
    yum install -y wget
    fileName=${URL_Download##*/}
    [ -f ${BASE_DIR}/${fileName} ] || wget ${URL_Download} -O ${BASE_DIR}/${fileName} || echo -e "\033[31m install mysql${port} failed \033[0m"
  else
    fileName=mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz
    [ -f ${BASE_DIR}/${fileName} ] || cp ${fileName}  ${BASE_DIR}/
  fi
  tarFile=${fileName%.*}
  [ -d ${BASE_DIR}/etc ] && rm -rf ${BASE_DIR}/etc/* ||   mkdir -p ${BASE_DIR}/etc
  [ -d ${DATA_DIR} ] && rm -rf ${DATA_DIR}/* || mkdir -p ${DATA_DIR}

  cd ${BASE_DIR} && xz -d ${fileName} && cd -
  [ -d ${BASE_DIR}/${tarFile%.*} ] || tar -xvf ${BASE_DIR}/${tarFile} -C ${BASE_DIR}/
  [ -d ${BASE_DIR}/${tarFile%%.*} ] || mv ${BASE_DIR}/${tarFile%.*} ${BASE_DIR}/${tarFile%%.*}
  [ -d ${BASE_DIR}/${tarFile%%.*}/etc ] || mkdir ${BASE_DIR}/${tarFile%%.*}/etc
  if [ -f  mysql.cnf ];then
    [ -f ${BASE_DIR}/${tarFile%%.*}/etc/mysql.cnf ] || mv mysql.cnf ${BASE_DIR}/${tarFile%%.*}/etc/
  else
    [ -f ${BASE_DIR}/${tarFile%%.*}/etc/mysql.cnf ] || (echo -e "\033[31m install mysql${port} failed, not found cnf \033[0m" exit 1)
  fi
  [ -f my.cnf ] && rm -f my.cnf
  cp ${BASE_DIR}/${tarFile%%.*}/etc/mysql.cnf my.cnf
  sed -i "s/3306/${port}/g" my.cnf
  mv -f my.cnf ${BASE_DIR}/${tarFile%%.*}/etc/my${port}.cnf

  cd ${BASE_DIR}
  id mysql || create_user #(echo -e "\033[31m please create mysql user \033[0m" && exit 1)
  chown -R mysql:mysql ${BASE_DIR}/${tarFile%%.*}
  cd ${BASE_DIR}/${tarFile%%.*}
  ./bin/mysqld --defaults-file=${BASE_DIR}/${tarFile%%.*}/etc/my${port}.cnf --basedir=${BASE_DIR} --datadir=${DATA_DIR}/mysql_${port} --initialize-insecure
  [ $? -ne 0 ] && echo -e "\033[31m install mysql${port} failed \033[0m"
  echo -e "\033[32m install mysql${port} successful \033[0m"
  echo -e "\033[32m for convenience please create alias to /root/.bashrc\033[0m"
  echo "alias mysql${port}=\"${BASE_DIR}/${tarFile%%.*}/bin/mysql -S ${DATA_DIR}/mysql_${port}/mysql.sock\"" >> /root/.bashrc
  source /root/.bashrc
  # start mysql
  ./bin/mysqld_safe --defaults-file=${BASE_DIR}/${tarFile%%.*}/etc/my${port}.cnf --user=mysql &
  # mysql
  #mysql${port}
  #create user 'admin'@'%' identified by 'admin';
  #grant all privileges on *.* to admin@'%' with grant option;
}

tarxz_install